package com.zuipin.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.BalanceRecord;
import com.zuipin.entity.IntegralRecord;
import com.zuipin.entity.RuleSetUseLog;
import com.zuipin.entity.SysUser;
import com.zuipin.entity.shoppingCart.RuleType;
import com.zuipin.enums.BalanceType;
import com.zuipin.enums.IntegralType;
import com.zuipin.enums.PayType;
import com.zuipin.enums.PrizeType;
import com.zuipin.enums.TimeDotType;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.mapper.RuleSetUseLogMapper;
import com.zuipin.service.IBalanceRecordService;
import com.zuipin.service.IDrawNumService;
import com.zuipin.service.IGiftGivingService;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.IRedPacketService;
import com.zuipin.util.StringUtil;

/**
 * 根据订单id和订单状态赠送礼物
 * @author zhouhuihang
 *
 */

@Service
public class GiftGivingServiceImpl implements IGiftGivingService {
	@Resource
	private RuleSetUseLogMapper		ruleSetUseLogMapper;
	@Resource
	private IRedPacketService		redPacketService;
	@Resource
	private IIntegralRecordService	integralRecordService;
	@Resource
	private IBalanceRecordService	balanceRecordService;
	@Resource
	private IDrawNumService			drawNumService;
	
	private final static Logger		logger	= LoggerFactory.getLogger(GiftGivingServiceImpl.class);
	
	// 根据订单id和订单状态赠送
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void doGiftGiving(Long orderNo, Long memberId, Long sysId, Enum state, String oddNumbers) throws CustomException {
		
		List<RuleSetUseLog> ruleSetUseLogs = null;
		if (PayType.ONLINE.toString().equals(state.toString())) {
			ruleSetUseLogs = ruleSetUseLogMapper.findByOrderNo(orderNo, "PAY_SUCCESS_NH");
			List<RuleSetUseLog> ruleSetUseLogs2 = ruleSetUseLogMapper.findByOrderNo(orderNo, "PAY_SUCCESS");
			if (ruleSetUseLogs2 != null && ruleSetUseLogs2.size() > 0) {
				ruleSetUseLogs.addAll(ruleSetUseLogs2);
			}
		} else if (PayType.CASH_DELIVERY.toString().equals(state.toString())) {
			ruleSetUseLogs = ruleSetUseLogMapper.findByOrderNo(orderNo, "PAY_SUCCESS");
		} else if (TimeDotType.ORDER_COMPLETE.toString().equals(state.toString())) {
			ruleSetUseLogs = ruleSetUseLogMapper.findByOrderNo(orderNo, "ORDER_COMPLETE");
		}
		if (ruleSetUseLogs != null) {
			for (RuleSetUseLog ruleSetUseLog : ruleSetUseLogs) {
				if (PrizeType.GIVE_INTEGRAL.toString().equals(ruleSetUseLog.getShowType()) && ruleSetUseLog.getIsGiving().equals(RuleSetUseLog.IS_GIVING_NO_0)) {
					// 赠送积分
					integralRecordService.addIntegralRecord(memberId, sysId, null, null, ruleSetUseLog.getGiveNum().intValue(), IntegralType.GET_SHOPPING, "购物", "订单号", oddNumbers,
							IntegralRecord.IS_BUY_NO);
					// 修改状态
					ruleSetUseLog.setIsGiving(RuleSetUseLog.IS_GIVING_YES_1);
					ruleSetUseLogMapper.update(ruleSetUseLog);
				}
				if (PrizeType.GIVE_TOPUP_BALANCE.toString().equals(ruleSetUseLog.getShowType()) && ruleSetUseLog.getIsGiving().equals(RuleSetUseLog.IS_GIVING_NO_0)) {
					// 赠送充值余额
					balanceRecordService.updateBalance(memberId, sysId, null, null, ruleSetUseLog.getGiveNum(), BalanceType.CART_GIVE, "购物", "订单号", oddNumbers,
							BalanceRecord.IS_BUY_NO);
					// 修改状态
					ruleSetUseLog.setIsGiving(RuleSetUseLog.IS_GIVING_YES_1);
					ruleSetUseLogMapper.update(ruleSetUseLog);
				}
				
				if (PrizeType.GIVE_RED_PACKET.toString().equals(ruleSetUseLog.getShowType()) && ruleSetUseLog.getIsGiving().equals(RuleSetUseLog.IS_GIVING_NO_0)) {
					// 赠送红包
					String[] no = ruleSetUseLog.getGiveRuleSetIds().split(",");
					Long[] str2 = new Long[no.length];
					for (int i = 0; i < no.length; i++) {
						str2[i] = Long.valueOf(no[i]);
					}
					// for (int i = 0; i < str2.length; i++) {
					List<Long> userList = new ArrayList<Long>();
					Collections.addAll(userList, str2);
					try {
						redPacketService.sendRedPacket(userList, sysId, ruleSetUseLog.getGiveNum().intValue(), memberId, SysUser.SYS_USER, ruleSetUseLog.getId(),
								RuleType.CART.toString() + "_" + PrizeType.GIVE_RED_PACKET.toString(), orderNo);
						ruleSetUseLog.setIsGiving(RuleSetUseLog.IS_GIVING_YES_1);
						ruleSetUseLogMapper.update(ruleSetUseLog);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						logger.info("购物车赠送异常{}", e.toString());
					}
					
				}
				if (PrizeType.GIVE_DRAW_NUM.toString().equals(ruleSetUseLog.getShowType().trim()) && ruleSetUseLog.getIsGiving().equals(RuleSetUseLog.IS_GIVING_NO_0)) {
					// 赠送抽奖次数
					if (!StringUtil.isBlank(ruleSetUseLog.getGiveRuleSetIds()) && ruleSetUseLog.getGiveNum() != null && ruleSetUseLog.getGiveNum().intValue() > 0) {
						String[] no = ruleSetUseLog.getGiveRuleSetIds().split(",");
						for (int i = 0; i < no.length; i++) {
							drawNumService.modityDrawNum(memberId, Long.valueOf(no[i]), sysId, ruleSetUseLog.getGiveNum().intValue(), null);
							// 修改状态
							ruleSetUseLog.setIsGiving(RuleSetUseLog.IS_GIVING_YES_1);
							ruleSetUseLogMapper.update(ruleSetUseLog);
						}
					}
				}
			}
		} else {
			// 该订单没有赠送商品
			logger.info("订单:{}没有购物车规则赠送", orderNo);
		}
		
	}
	
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void doGiftGivingByPay(Long orderNo, Long memberId, Long sysId, Enum state, String oddNumbers) {
		try {
			doGiftGiving(orderNo, memberId, sysId, state, oddNumbers);
		} catch (Exception e) {
			logger.info("购物车规则赠送失败了,异常{}", e.toString());
		}
	}
	
}